//
//  UIColor+RGB.m
//  Psd
//
//  Created by leirz on 14-8-24.
//  Copyright (c) 2014年 psd. All rights reserved.
//

#import "UIColor+RGB.h"

@implementation UIColor (RGB)

+ (UIColor *)colorWithString:(NSString *)colorString
{
    return [self colorWithString:colorString alpha:1.0];
}

+ (UIColor *)colorWithString:(NSString *)colorString alpha:(CGFloat)alpha;
{
    static NSDictionary *data;
    UIColor *color = nil;
    if (data != nil) {
        color = [data objectForKey:colorString];
        if (color != nil) {
            return color;
        }
    } else {
        data = [[NSMutableDictionary alloc] init];
    }
    if ([colorString hasPrefix:@"#"] && colorString.length == 7) {
        NSString *hexString = [NSString stringWithFormat:@"0x%@", [colorString substringFromIndex:1]];
        NSInteger hexValue = strtoul([hexString UTF8String], 0, 0);
        
        CGFloat r=(hexValue & 0xFF0000) >> 16;
         CGFloat g=(hexValue & 0xFF00) >> 8;
         CGFloat b=hexValue & 0xFF;
        color = [UIColor colorWithRed:(float)r / 255
                                green:(float)g / 255
                                 blue:(float)b / 255
                                alpha:alpha];
        [data setValue:color forKey:colorString];
        return color;
    }
    return [UIColor whiteColor];
}

+ (UIImage *)imageWithString:(NSString *)colorString size:(CGSize)size
{
    UIColor *color = [self colorWithString:colorString];
    return [UIColor imageWithColor:color size:size];
}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGSize size = CGSizeMake(1.0, 1.0);
    return [UIColor imageWithColor:color size:size];
}

+(UIColor*)randomColor
{
    float r  = arc4random()%256;
    float g  = arc4random()%256;
    float b  = arc4random()%256;
    return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1];
}


@end
